<template>
  <div class="body1">
    <div class="no-print el-button-print">
      <el-button @click="exportPDF">导出为pdf</el-button>
    </div>

    <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
      <div class="title">
        <div class="biaoti">法定代表人身份证明</div>
      </div>
      <div class="tableStyle1">

        <div style="height: 300px; line-height: 30px; margin-top: 50px;">
          <span>&nbsp;&nbsp;&nbsp;&nbsp;</span><input v-model="form.a1" :resize="'none'" autosize maxlength="5"
            class="inputStyle1" style="width: calc(7 * 5mm);font-family: 仿宋;font-size: 5mm;"
            type="textarea"><span>同志（身份证号：</span><input v-model="form.a2" :resize="'none'" autosize maxlength="26"
            class="inputStyle1" oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')"
            style="width: calc(13 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea"><span>）在</span><input
            v-model="form.a3" :resize="'none'" autosize maxlength="25" class="inputStyle1"
            style="width: calc(25 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea"><span>担任</span>
          <CrossRowInput v-model:value="form.a4" :line-config="a4Config"></CrossRowInput><span>职务。是我单位法定代表人。</span>
          <br><span>&nbsp;&nbsp;&nbsp;&nbsp;地址：</span><input v-model="form.a5" :resize="'none'" autosize maxlength="16"
            class="inputStyle1" style="width: calc(16 * 5mm);font-family: 仿宋;font-size: 5mm;"
            type="textarea">&nbsp;&nbsp;
          <span>电话：</span><input v-model="form.a6" :resize="'none'" autosize maxlength="14" class="inputStyle1"
            style="width: calc(7 * 5mm);font-family: 仿宋;font-size: 5mm;"
            oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')" type="textarea">
          <br><span>&nbsp;&nbsp;&nbsp;&nbsp;其他需要证明的内容：</span>
          <input v-model="form.a7" :resize="'none'" autosize maxlength="20" class="inputStyle1"
            style="width: calc(20 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
        </div>
        <div class="writ-height"></div>
        <div style="text-align: right; margin-top: 10px; margin-bottom: 60px;">
          <div class="seal-container">
            <span class="seal-name">（印&nbsp;&nbsp;章）</span>
            <div class="delivery-agency-div">
              <editable-textarea :text="form.date1" param-type="YYYYMMDD1" @send-to-parent="receiveFromChild" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
import EditableTextarea from "@/views/template/EditableTextarea";
import { agencyName, sealName } from "../../utils/publicName.js"

import CrossRowInput from "@/views/template/CrossRowInput";

export default {
  components: {
    EditableTextarea,
    CrossRowInput
  },

  data() {
    return {
      agencyName: agencyName,
      sealName: sealName,
      form: {},
      status: '', //当前文书的状态
      isPdfExport: false, //控制打印样式
      a4Config: {
        firstLine: { chars: 5 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 10 * 2 }
      },
    }
  },

  created() {
    window.parent.getTemplateData((data, status) => {
      this.form = data;
      this.status = status;
    })
    window.postForm = () => {
      this.postForm();
    }
  },

  mounted() {
    window.parent.changeTemplateDow();
  },

  methods: {
    // 导出为pdf
    exportPDF() {
      this.savePDF()
        .then((blob) => {

          const blobUrl = URL.createObjectURL(blob);

          // 先预览
          const previewWindow = window.open(blobUrl, '_blank');

          // 自动下载
          const fileName = `法定代表人身份证明.pdf`;
          const downloadLink = document.createElement('a');
          downloadLink.href = blobUrl;
          downloadLink.download = fileName;
          document.body.appendChild(downloadLink);
          downloadLink.click();
          document.body.removeChild(downloadLink);

          // 监听预览窗口关闭后释放内存
          if (previewWindow) {
            const timer = setInterval(() => {
              if (previewWindow.closed) {
                clearInterval(timer);
                URL.revokeObjectURL(blobUrl);
              }
            }, 1000);
          } else {
            setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
          }
        })
        .catch(error => {
          console.error('导出PDF出错:', error);
          alert('导出失败，请重试或联系管理员');
        });
    },
    savePDF() {
      this.isPdfExport = true; // 激活PDF样式
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          import('html2pdf.js').then((module) => {
            const html2pdf = module.default;

            //获取所有需要替换的 el-input
            const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

            //存储原始元素和它们的父节点，方便后续恢复
            const originalElements = [];

            elInputs.forEach((input) => {
              const div = document.createElement('div');
              div.style.whiteSpace = 'pre-wrap'; // 保留换行
              div.style.fontFamily = '仿宋';
              div.style.fontSize = '5mm';
              div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
              div.style.lineHeight = '1.3';

              // 替换 el-input，并存储原始元素
              originalElements.push({
                parent: input.parentNode,
                original: input,
                replacement: div,
              });
              input.parentNode.replaceChild(div, input);
            });

            // 配置选项
            const opt = {
              margin: 0,
              image: {
                type: 'jpeg',
                quality: 0.98
              },
              html2canvas: {
                scale: 2,
                logging: false,
                useCORS: true
              },
              jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'portrait'
              }
            };

            const element = document.getElementById('pdfDom');

            // 生成PDF Blob对象
            html2pdf()
              .set(opt)
              .from(element)
              .toPdf()
              .get('pdf')
              .then((pdf) => {
                const blob = pdf.output('blob');

                resolve(blob); // 返回Blob对象
              })
              .catch((error) => {
                reject(error);
              })
              .finally(() => {
                this.isPdfExport = false; // 恢复原始样式
                // 恢复原始input
                originalElements.forEach(({ parent, original, replacement }) => {
                  parent.replaceChild(original, replacement);
                });
              });
          }).catch((error) => {
            reject(error);
            this.isPdfExport = false;
            originalElements.forEach(({ parent, original, replacement }) => {
              parent.replaceChild(original, replacement);
            });
          });
        });
      });
    },
    //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
    postForm() {
      this.savePDF()
        .then((blob) => {


          // 创建FormData并添加文件
          const formData = new FormData();
          formData.append('file', blob, '法定代表人身份证明.pdf');

          window.parent.postTemplateDate(this.form, formData);
        })
        .catch(error => {
          console.error('整个保存PDF出错:', error);
        });
    },
    //选择日期时间
    receiveFromChild(data, type) {
      const TypeMap = {
        'YYYYMMDD1': 'date1',
      };
      if (TypeMap[type]) {
        this.form[TypeMap[type]] = data;
      }
    },
  }
}
</script>

<style scoped>
/*.delivery-agency-div {*/
/*font-family: "仿宋", serif;*/
/*font-size: 5mm;*/
/*margin-top: 10px;*/
/*position: relative;*/
/*top: 0px;*/
/*right: -20px;*/
/*}*/


:deep(.el-button-print .el-button) {
  display: inline-flex !important;
  visibility: visible !important;
  opacity: 1 !important;
  width: auto;
  min-width: 100px;
  height: auto;
  padding: 8px 15px;
  background: #fff !important;
  color: #000 !important;
  border: none;
}

:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden;
  line-height: 1.3;
  white-space: pre-wrap;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden !important;
  resize: none !important;
  height: auto !important;
}

.input-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.inputStyleNoLine {
  border: none;
  outline: none;
  padding: 0px;
}

.typeSpan {
  cursor: pointer;
  font-size: 5mm;
}
</style>
